/**
 * 角色管理相关API
 */

import { http } from "@/utils/http";

// 权限信息类型
export interface PermissionInfo {
  id: number;
  permKey: string;
  permName: string;
  description: string;
  createBy?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
}

// 角色信息类型
export interface RoleInfo {
  id: number;
  roleKey: string;
  roleName: string;
  description: string;
  status: string;
  statusText?: string;
  createBy?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
  permissions?: PermissionInfo[];
  userCount?: number;
  canDelete?: boolean;
}

// 分页查询参数类型
export interface RoleListParams {
  current?: number;
  size?: number;
  roleKey?: string;
  roleName?: string;
  status?: string;
  permissionId?: number;
}

// 分页响应数据类型
export interface PageData<T> {
  records: T[];
  total: number;
  current: number;
  size: number;
  pages: number;
  hasPrevious: boolean;
  hasNext: boolean;
}

// 通用响应类型
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data?: T;
  timestamp?: number;
}

// 角色列表响应类型
export type RoleListResult = ApiResponse<RoleInfo[]>;
export type RolePageResult = ApiResponse<PageData<RoleInfo>>;

// 角色详情响应类型
export type RoleDetailResult = ApiResponse<RoleInfo>;

// 权限列表响应类型
export type PermissionListResult = ApiResponse<PermissionInfo[]>;

// 角色分配响应类型
export type RoleAssignResult = ApiResponse;

// 创建角色参数类型
export interface CreateRoleParams {
  roleKey: string;
  roleName: string;
  description?: string;
  status?: string;
  permissionIds?: number[];
}

// 更新角色参数类型
export interface UpdateRoleParams {
  roleName?: string;
  description?: string;
  status?: string;
  permissionIds?: number[];
}

// ==================== 角色管理接口 ====================

/**
 * 分页查询角色列表
 * @param params 查询参数
 * @returns Promise<RolePageResult>
 */
export const getRoleListApi = (
  params: RoleListParams = {}
): Promise<RolePageResult> => {
  return http.request<RolePageResult>("get", "/admin/roles/list", { params });
};

/**
 * 获取角色详情
 * @param roleId 角色ID
 * @returns Promise<RoleDetailResult>
 */
export const getRoleDetailApi = (roleId: number): Promise<RoleDetailResult> => {
  return http.request<RoleDetailResult>("get", `/admin/roles/${roleId}/detail`);
};

/**
 * 创建角色
 * @param params 创建参数
 * @returns Promise<ApiResponse>
 */
export const createRoleApi = (
  params: CreateRoleParams
): Promise<ApiResponse> => {
  return http.request<ApiResponse>("post", "/admin/roles/createRole", {
    data: params
  });
};

/**
 * 更新角色
 * @param roleId 角色ID
 * @param params 更新参数
 * @returns Promise<ApiResponse>
 */
export const updateRoleApi = (
  roleId: number,
  params: UpdateRoleParams
): Promise<ApiResponse> => {
  return http.request<ApiResponse>("put", `/admin/roles/${roleId}/update`, {
    data: params
  });
};

/**
 * 删除角色
 * @param roleId 角色ID
 * @returns Promise<ApiResponse>
 */
export const deleteRoleApi = (roleId: number): Promise<ApiResponse> => {
  return http.request<ApiResponse>("delete", `/admin/roles/${roleId}/delete`);
};

/**
 * 批量删除角色
 * @param roleIds 角色ID数组
 * @returns Promise<ApiResponse>
 */
export const batchDeleteRolesApi = (
  roleIds: number[]
): Promise<ApiResponse> => {
  return http.request<ApiResponse>("delete", "/admin/roles/batchDelete", {
    data: roleIds
  });
};

/**
 * 更新角色状态
 * @param roleId 角色ID
 * @param status 状态
 * @returns Promise<ApiResponse>
 */
export const updateRoleStatusApi = (
  roleId: number,
  status: string
): Promise<ApiResponse> => {
  return http.request<ApiResponse>(
    "put",
    `/admin/roles/${roleId}/updateStatus`,
    { params: { status } }
  );
};

/**
 * 检查角色标识是否存在
 * @param roleKey 角色标识
 * @param excludeId 排除的角色ID（编辑时使用）
 * @returns Promise<ApiResponse<boolean>>
 */
export const checkRoleKeyApi = (
  roleKey: string,
  excludeId?: number
): Promise<ApiResponse<boolean>> => {
  const params: any = { roleKey };
  if (excludeId) {
    params.excludeId = excludeId;
  }
  return http.request<ApiResponse<boolean>>(
    "get",
    "/admin/roles/checkRoleKey",
    { params }
  );
};

/**
 * 获取所有角色（下拉选择用）
 * @returns Promise<RoleListResult>
 */
export const getAllRolesForSelectApi = (): Promise<RoleListResult> => {
  return http.request<RoleListResult>("get", "/admin/roles/getAllForSelect");
};

/**
 * 获取可用角色列表（兼容旧接口）
 * @returns Promise<RoleListResult>
 */
export const getAvailableRolesApi = (): Promise<RoleListResult> => {
  return getAllRolesForSelectApi();
};

/**
 * 获取用户角色列表
 * @param userId 用户ID
 * @returns Promise<RoleListResult>
 */
export const getUserRolesApi = (userId: number): Promise<RoleListResult> => {
  if (!userId || userId <= 0) {
    console.error("无效的用户ID:", userId);
    return Promise.reject(new Error("用户ID不能为空"));
  }

  return http.request<RoleListResult>("get", `/admin/users/${userId}/getRoles`);
};

/**
 * 为用户分配角色
 * @param userId 用户ID
 * @param roleIds 角色ID数组
 * @returns Promise<RoleAssignResult>
 */
export const assignRolesToUserApi = (
  userId: number,
  roleIds: number[]
): Promise<RoleAssignResult> => {
  if (!userId || userId <= 0) {
    console.error("无效的用户ID:", userId);
    return Promise.reject(new Error("用户ID不能为空"));
  }

  if (!Array.isArray(roleIds)) {
    console.error("角色ID必须是数组:", roleIds);
    return Promise.reject(new Error("角色ID必须是数组"));
  }

  return http.request<RoleAssignResult>(
    "post",
    `/admin/users/${userId}/assignRoles`,
    {
      data: roleIds
    }
  );
};

// ==================== 角色权限管理接口 ====================

/**
 * 获取角色权限列表
 * @param roleId 角色ID
 * @returns Promise<PermissionListResult>
 */
export const getRolePermissionsApi = (
  roleId: number
): Promise<PermissionListResult> => {
  return http.request<PermissionListResult>(
    "get",
    `/admin/roles/${roleId}/getPermissions`
  );
};

/**
 * 为角色分配权限
 * @param roleId 角色ID
 * @param permissionIds 权限ID数组
 * @returns Promise<ApiResponse>
 */
export const assignPermissionsToRoleApi = (
  roleId: number,
  permissionIds: number[]
): Promise<ApiResponse> => {
  return http.request<ApiResponse>(
    "post",
    `/admin/roles/${roleId}/assignPermissions`,
    { data: permissionIds }
  );
};

/**
 * 移除角色所有权限
 * @param roleId 角色ID
 * @returns Promise<ApiResponse>
 */
export const removeAllRolePermissionsApi = (
  roleId: number
): Promise<ApiResponse> => {
  return http.request<ApiResponse>(
    "delete",
    `/admin/roles/${roleId}/removeAllPermissions`
  );
};

/**
 * 获取所有权限列表
 * @returns Promise<PermissionListResult>
 */
export const getAllPermissionsApi = (): Promise<PermissionListResult> => {
  console.log(`API调用: getAllPermissionsApi`);
  return http.request<PermissionListResult>(
    "get",
    "/admin/roles/getAllPermissions"
  );
};

/**
 * 角色管理工具类
 */
export class RoleManagementUtils {
  /**
   * 格式化角色状态
   * @param status 状态值
   * @returns string
   */
  static formatRoleStatus(status: string): string {
    switch (status) {
      case "0":
        return "正常";
      case "1":
        return "停用";
      default:
        return "未知";
    }
  }

  /**
   * 获取角色状态标签类型
   * @param status 状态值
   * @returns string
   */
  static getRoleStatusType(status: string): string {
    switch (status) {
      case "0":
        return "success";
      case "1":
        return "danger";
      default:
        return "info";
    }
  }

  /**
   * 检查角色是否为系统角色
   * @param roleKey 角色标识
   * @returns boolean
   */
  static isSystemRole(roleKey: string): boolean {
    const systemRoles = ["admin", "system"];
    return systemRoles.includes(roleKey);
  }

  /**
   * 格式化角色显示名称
   * @param role 角色信息
   * @returns string
   */
  static formatRoleDisplayName(role: RoleInfo): string {
    return `${role.roleName}${role.description ? ` (${role.description})` : ""}`;
  }

  /**
   * 比较两个角色数组是否相同
   * @param roles1 角色数组1
   * @param roles2 角色数组2
   * @returns boolean
   */
  static compareRoleArrays(roles1: number[], roles2: number[]): boolean {
    if (roles1.length !== roles2.length) {
      return false;
    }

    const sorted1 = [...roles1].sort();
    const sorted2 = [...roles2].sort();

    return sorted1.every((id, index) => id === sorted2[index]);
  }

  /**
   * 从角色列表中提取角色ID数组
   * @param roles 角色列表
   * @returns number[]
   */
  static extractRoleIds(roles: RoleInfo[]): number[] {
    return roles.map(role => role.id);
  }

  /**
   * 根据角色ID数组获取角色名称数组
   * @param roleIds 角色ID数组
   * @param availableRoles 可用角色列表
   * @returns string[]
   */
  static getRoleNamesByIds(
    roleIds: number[],
    availableRoles: RoleInfo[]
  ): string[] {
    return roleIds
      .map(id => availableRoles.find(role => role.id === id))
      .filter(role => role !== undefined)
      .map(role => role!.roleName);
  }

  /**
   * 验证角色ID是否有效
   * @param roleIds 角色ID数组
   * @param availableRoles 可用角色列表
   * @returns { valid: boolean, invalidIds: number[] }
   */
  static validateRoleIds(
    roleIds: number[],
    availableRoles: RoleInfo[]
  ): { valid: boolean; invalidIds: number[] } {
    const availableIds = availableRoles.map(role => role.id);
    const invalidIds = roleIds.filter(id => !availableIds.includes(id));

    return {
      valid: invalidIds.length === 0,
      invalidIds
    };
  }

  /**
   * 验证角色标识格式
   * @param roleKey 角色标识
   * @returns boolean
   */
  static validateRoleKey(roleKey: string): boolean {
    if (!roleKey || roleKey.length < 2 || roleKey.length > 50) {
      return false;
    }
    // 只能包含字母、数字和下划线
    return /^[a-zA-Z0-9_]+$/.test(roleKey);
  }

  /**
   * 验证角色名称格式
   * @param roleName 角色名称
   * @returns boolean
   */
  static validateRoleName(roleName: string): boolean {
    return roleName && roleName.length >= 2 && roleName.length <= 100;
  }

  /**
   * 验证角色描述格式
   * @param description 角色描述
   * @returns boolean
   */
  static validateRoleDescription(description?: string): boolean {
    if (!description) return true; // 描述是可选的
    return description.length <= 500;
  }

  /**
   * 获取角色状态选项
   * @returns Array<{label: string, value: string}>
   */
  static getRoleStatusOptions() {
    return [
      { label: "正常", value: "0" },
      { label: "停用", value: "1" }
    ];
  }

  /**
   * 检查角色是否可以删除
   * @param role 角色信息
   * @returns boolean
   */
  static canDeleteRole(role: RoleInfo): boolean {
    // 如果有canDelete字段，直接使用
    if (role.canDelete !== undefined) {
      return role.canDelete;
    }
    // 否则根据用户数量和系统角色判断
    return (
      !this.isSystemRole(role.roleKey) &&
      (role.userCount === 0 || role.userCount === undefined)
    );
  }

  /**
   * 格式化权限显示名称
   * @param permission 权限信息
   * @returns string
   */
  static formatPermissionDisplayName(permission: PermissionInfo): string {
    return `${permission.permName}${permission.description ? ` (${permission.description})` : ""}`;
  }

  /**
   * 从权限列表中提取权限ID数组
   * @param permissions 权限列表
   * @returns number[]
   */
  static extractPermissionIds(permissions: PermissionInfo[]): number[] {
    return permissions.map(permission => permission.id);
  }
}
